<script lang="ts" setup>
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { VuePrintNext } from 'vue-print-next'
import { sendServiceData } from '../../common/service'
import { callLater, createOID } from '../../common/utils/normalUtils'

  const emit = defineEmits(['loading', 'ready', 'error', 'close'])

  const props = defineProps({
    dataSource: {
      type: Array,
      default: function() {
        return []
      }
    },
    params: {
      type: Object,
      default: function() {
        return null
      }
    },
    queryMethod: {
      type: Function,
      default: function() {
        return null
      }
    },
    page: {
      type: Boolean,
      default: true
    },
    autoQuery: {
      type: Boolean,
      default: true
    },
    printParams: {
      type: Object,
      default: function() {
        return null
      }
    },
    autoPrint: {
      type: Boolean,
      default: true
    },
    pageWidth: {
      type: Number,
      default: function() {
        return 1000
      }
    },
    scale: {
      type: Number,
      default: 1
    }
  })

  const state = reactive({
    isLoading: false,
    autoId: createOID(),
    dataSource: [],
    hiddCol: false,
    length: 0,
    printOptions: {

    }
  })

  let _cid:any = ''

  const setLoading = (val:boolean) => {
    state.isLoading = val
    emit('loading', val)
  }

  const queryList = async () => {
    const send = props.page ? { pageNum: 1 } : {}
    if (props.params)Object.assign(send, props.params)
    const result = await sendServiceData(props.queryMethod, send, setLoading, true, true)
    if (result === null) {
      emit('error')
      return
    }
    const list = result.rows || []
    state.dataSource = list
    state.length = list.length
    startRender()
  }


  /**
   * 检测列表渲染状态
   */
  const startRender = () => {
      _cid = setInterval(() => {
         if (!_cid) return
         const dom = document.getElementById(state.autoId + '_' + (state.length - 1))
         if (dom) {
           stopRender()
           emit('ready', state.autoId)
           if (props.autoPrint)printView()
         }
      }, 200)
  }

  const stopRender = () => {
    if (_cid)clearInterval(_cid)
    _cid = null
  }


  const printView = () => {
    const params = props.printParams || {}

    Object.assign(state.printOptions, {
      ...params,
      id: state.autoId,
      zIndex: 99999999,
      extraCss: '_hid_col',
      closeCallback: () => {
        if (params.closeCallback) params.closeCallback()
        emit('close')
      }
    })
    const dd = document.getElementById(state.autoId)
    const options:any = {
        ...params,
        el: dd,
        zIndex: 99999999,
        extraCss: '_hid_col',
        closeCallback: () => {
          if (params.closeCallback) params.closeCallback()
          emit('close')
        }
    }
    state.hiddCol = true
    callLater(() => {
      const print = new VuePrintNext(options)
    }, 200)

    // printRef.value.click()
  }

  onMounted(() => {
     queryList()
  })

  onUnmounted(() => {
    stopRender()
  })

  defineExpose({
    print: printView
  })

const printBoxStyle = computed(() => {
  const scale = 1// 748.3 / props.pageWidth
  return {
    width: props.pageWidth + 'px',
    transform: `scale(${scale},${scale})`
  }
})

</script>

<template>
  <div class="print-box">
    <div :id="state.autoId" class="print-table" :style="printBoxStyle">
      <el-table :data="state.dataSource"
                border
                stripe
                size="small"
                :style="{width:pageWidth+'px',height:'auto'}">
        <el-table-column v-if="!state.hiddCol"
                         width="0"
                         align="center"
                         class="_hid_col">
          <template #default="{$index}">
            <span :id="state.autoId+'_'+$index" class="_hid_col" />
          </template>
        </el-table-column>
        <slot />
      </el-table>
    </div>
  </div>
</template>

<style lang="scss">
._hid_col{
  overflow: hidden;
  width:0;
  height:0;
}
</style>

<style scoped lang="scss">
  .print-box {
    width:0;
    height:0;
    position: relative;
    overflow: hidden;
  }
  .print-table{
    transform-origin: 0 0;
    width:100%;
    height:auto;
    box-sizing: border-box;
    overflow: hidden;
  }
  //@page{
  //  size:auto;
  //  margin: 0mm;
  //}
</style>
